package com.swh.user.service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.swh.base.entity.Result;
import com.swh.base.entity.StatusCode;
import com.swh.user.entity.TbAdmin;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.swh.utils.IdUtil;
import com.swh.user.dao.TbUserDao;
import com.swh.user.entity.TbUser;

/**
 * @author swh
 * @Description 用户 服务层
 * @date 2021-01-15 17:27:10
 */
@Service
public class TbUserService {

    @Autowired
    private TbUserDao tbUserDao;

    @Autowired
    private IdUtil idUtil;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitMessagingTemplate rabbitMessagingTemplate;

    @Autowired
    TbUserDao userDao;

    @Autowired
    BCryptPasswordEncoder encoder;


    /**
     * 用户登录
     *
     * @return
     **/
    public TbUser login(String loginname, String password) {
        TbUser user = tbUserDao.findByMobile(loginname);
        if (user != null && encoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }


    /**
     * 用户注册
     *
     * @return
     **/
    public Result register(TbUser user, String code) {


        Object ObjReids = redisTemplate.opsForValue().get("ktc_s" + user.getMobile());
        if (ObjReids == null) {
            return new Result(StatusCode.ERROR, "验证码过期");
        } else {
            ObjReids = ObjReids.toString();
            System.out.println(ObjReids);
            if (code.equals(ObjReids)) {
                user.setId(idUtil.nextId() + "");
                user.setFollowcount(0);//关注数
                user.setFanscount(0);//粉丝数
                user.setOnline(0L);//在线时长

                user.setRegdate(new Date());//注册日期
                user.setUpdatedate(new Date());//更新日期
                user.setLastdate(new Date());//最后登陆日期

                TbUser mobile = tbUserDao.findByMobile(user.getMobile());
                if (mobile!=null) {
                    return new Result(StatusCode.OK, "电话号码已经存在");
                }
                user.setPassword(encoder.encode(user.getPassword()));

                userDao.save(user);

                redisTemplate.delete("ktc_s" + user.getMobile());
            } else {
                return new Result(StatusCode.OK, "验证码错误");
            }
        }
        return new Result(StatusCode.OK, "注册成功");
    }


    /**
     * 发送验证码
     *
     * @return
     **/
    public void sendsms(String mobile) {

        //生成6位随机数 (common-lang包下)
        String code = RandomStringUtils.randomNumeric(4);
        System.out.println(code);

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //把手机号和验证码存入redis
        redisTemplate.opsForValue().set("ktc_s" + mobile, code, 60, TimeUnit.SECONDS);

        //把手机号和验证码发送给MQ
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("mobile", mobile);
        dataMap.put("code", code);

        rabbitMessagingTemplate.convertAndSend("ktc_s", dataMap);

    }

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<TbUser> findAll() {
        return tbUserDao.findAll();
    }

    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<TbUser> findSearch(Map whereMap, int page, int size) {
        Specification<TbUser> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return tbUserDao.findAll(specification, pageRequest);
    }

    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<TbUser> findSearch(Map whereMap) {
        Specification<TbUser> specification = createSpecification(whereMap);
        return tbUserDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public TbUser findById(String id) {
        return tbUserDao.findById(id).get();
    }

    /**
     * 增加
     *
     * @param tbUser
     */
    public void add(TbUser tbUser) {
        tbUser.setId(idUtil.nextId() + "");
        tbUserDao.save(tbUser);
    }

    /**
     * 修改
     *
     * @param tbUser
     */
    public void update(TbUser tbUser) {
        tbUserDao.save(tbUser);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        tbUserDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<TbUser> createSpecification(Map searchMap) {

        return new Specification<TbUser>() {

            @Override
            public Predicate toPredicate(Root<TbUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                //手机号码
                if (searchMap.get("mobile") != null && !"".equals(searchMap.get("mobile"))) {
                    predicateList.add(cb.like(root.get("mobile").as(String.class), "%" + (String) searchMap.get("mobile") + "%"));
                }
                //密码
                if (searchMap.get("password") != null && !"".equals(searchMap.get("password"))) {
                    predicateList.add(cb.like(root.get("password").as(String.class), "%" + (String) searchMap.get("password") + "%"));
                }
                //昵称
                if (searchMap.get("nickname") != null && !"".equals(searchMap.get("nickname"))) {
                    predicateList.add(cb.like(root.get("nickname").as(String.class), "%" + (String) searchMap.get("nickname") + "%"));
                }
                //性别
                if (searchMap.get("sex") != null && !"".equals(searchMap.get("sex"))) {
                    predicateList.add(cb.like(root.get("sex").as(String.class), "%" + (String) searchMap.get("sex") + "%"));
                }
                //出生年月日
                if (searchMap.get("birthday") != null && !"".equals(searchMap.get("birthday"))) {
                    predicateList.add(cb.like(root.get("birthday").as(String.class), "%" + (String) searchMap.get("birthday") + "%"));
                }
                //头像
                if (searchMap.get("avatar") != null && !"".equals(searchMap.get("avatar"))) {
                    predicateList.add(cb.like(root.get("avatar").as(String.class), "%" + (String) searchMap.get("avatar") + "%"));
                }
                //E-Mail
                if (searchMap.get("email") != null && !"".equals(searchMap.get("email"))) {
                    predicateList.add(cb.like(root.get("email").as(String.class), "%" + (String) searchMap.get("email") + "%"));
                }
                //注册日期
                if (searchMap.get("regdate") != null && !"".equals(searchMap.get("regdate"))) {
                    predicateList.add(cb.like(root.get("regdate").as(String.class), "%" + (String) searchMap.get("regdate") + "%"));
                }
                //修改日期
                if (searchMap.get("updatedate") != null && !"".equals(searchMap.get("updatedate"))) {
                    predicateList.add(cb.like(root.get("updatedate").as(String.class), "%" + (String) searchMap.get("updatedate") + "%"));
                }
                //最后登陆日期
                if (searchMap.get("lastdate") != null && !"".equals(searchMap.get("lastdate"))) {
                    predicateList.add(cb.like(root.get("lastdate").as(String.class), "%" + (String) searchMap.get("lastdate") + "%"));
                }
                //在线时长（分钟）
                if (searchMap.get("online") != null && !"".equals(searchMap.get("online"))) {
                    predicateList.add(cb.like(root.get("online").as(String.class), "%" + (String) searchMap.get("online") + "%"));
                }
                //兴趣
                if (searchMap.get("interest") != null && !"".equals(searchMap.get("interest"))) {
                    predicateList.add(cb.like(root.get("interest").as(String.class), "%" + (String) searchMap.get("interest") + "%"));
                }
                //个性
                if (searchMap.get("personality") != null && !"".equals(searchMap.get("personality"))) {
                    predicateList.add(cb.like(root.get("personality").as(String.class), "%" + (String) searchMap.get("personality") + "%"));
                }
                //粉丝数
                if (searchMap.get("fanscount") != null && !"".equals(searchMap.get("fanscount"))) {
                    predicateList.add(cb.like(root.get("fanscount").as(String.class), "%" + (String) searchMap.get("fanscount") + "%"));
                }
                //关注数
                if (searchMap.get("followcount") != null && !"".equals(searchMap.get("followcount"))) {
                    predicateList.add(cb.like(root.get("followcount").as(String.class), "%" + (String) searchMap.get("followcount") + "%"));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

}
